#pragma once
#include <iostream>

#include <cstdio>
#include <string>
#include <fstream>
#include <sstream>
#include <memory>
#include <filesystem> //C++17
#include <unistd.h>
#include <time.h>
#include "mutex.hpp"

namespace LogModule
{

    // 记录日志文件默认名字与默认路径
    const std::string defaultlogname = "log.txt";
    const std::string defaultlogpath = "./log/";

    // 定义枚举体日志等级
    enum class LogLevel
    {
        DEBUG = 1,
        INFO,
        WARN,
        ERROR,
        FATAL
    };

    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;                     // 进行虚析构
        virtual void Synclog(const std::string &message) = 0; // 定义一个统一的调用接口以便后续子类重新定义实现多态
    };
    using namespace MutexModule;
    class ConsoleLogStrategy : public LogStrategy // 控制台策略
    {
    public:
        ConsoleLogStrategy()
        {
        }
        ~ConsoleLogStrategy()
        {
        }

        void Synclog(const std::string &message) // 打印我们的信息到控制台
        {
            LockGuard lockguard(_lock); // 防止多个进程打印乱码
            std::cout << message << std::endl;
        }

    private:
        Mutex _lock; // 互斥量锁
    };

    class FileLogStrategy : public LogStrategy // 文件（硬盘级）策略
    {
    public:
        FileLogStrategy(const std::string &logpath = defaultlogpath, const std::string &logname = defaultlogname)
            : _logpath(logpath),
              _logname(logname)
        {
            if (std::filesystem::exists(_logpath))
            {
                return; // 存在我们就直接返回防止重复创建路径
            }
            else
            {
                LockGuard LockGuard(_mutex);
                try
                {
                    std::filesystem::create_directory(_logpath);
                }
                catch (const std::filesystem::filesystem_error &e)
                {
                    std::cerr << "创建日志目录失败: " << e.what() << std::endl;
                }
            }
        }
        ~FileLogStrategy()
        {
        }
        void Synclog(const std::string &message)
        {
            LockGuard LockGuard(_mutex);
            std::string log = _logpath + _logname; // 合并文件路径与文件名
            std::ofstream out(log, std::ios::app); // 追加写入使用app
            if (!out.is_open())
            {
                return; // 如果打开失败
            }
            out << message << "\n";
            out.close(); // 关闭文件流
        }

    private:
        std::string _logpath;
        std::string _logname;

        Mutex _mutex;
    };
    std::string GetCurrentTime()
    {
        time_t t = ::time(nullptr);
        struct tm ttm;
        ::localtime_r(&t, &ttm); // ttm是一个输出型参数
        // 定义缓冲区将数据格式化
        char buffer[1024];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 ttm.tm_year + 1900, // 这里注意给的年份是减去了1900的所以真实年要加回来，月份也是如此
                 ttm.tm_mon + 1,
                 ttm.tm_mday,
                 ttm.tm_hour,
                 ttm.tm_min,
                 ttm.tm_sec);
        return buffer;
    }

    std::string Level_to_string(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARN:
            return "WARN";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "NONE";
        }
    }
    class Log
    {
    public:
        Log()
        {
            // 默认采用ConsoleLogStrategy策略
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableConsoleLog()
        {
            LockGuard lockguard(_mutex);
            _strategy = std::make_shared<ConsoleLogStrategy>();
        }
        void EnableFileLog()
        {
            LockGuard lockguard(_mutex);
            _strategy = std::make_shared<FileLogStrategy>();
        }
        ~Log() {}

        class logmessage
        {
        public:
            logmessage(LogLevel level, const std::string &filename, const int &line, Log &log) // 这里新增了一个参数
                : _level(level),
                  _line(line),
                  _time(GetCurrentTime()),
                  pid(getpid()),
                  _filename(filename),
                  _log(log) // 负责给你的log进行初始化，方便析构根据这个调用
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _time << "] "
                         << "[" << Level_to_string(_level) << "] "
                         << "[" << pid << "] "
                         << "[" << _filename << "] "
                         << "[" << _line << "] - ";
                _loginfo = ssbuffer.str();
            }

            template <typename T>
            logmessage &operator<<(const T &message)
            {
                std::stringstream ss;
                ss << message;
                _loginfo += ss.str();

                return *this;
            }

            ~logmessage()
            {
                if (_log._strategy) // 如果该智能指针存在
                {
                    _log._strategy->Synclog(_loginfo); // 调用该函数指针所指向策略的Synclog函数，实现多态
                }
            }

        private:
            std::string _time;     // 时间
            LogLevel _level;       // 日志等级
            pid_t pid;             // 进程pid
            std::string _filename; // 源文件名称
            int _line;             // 行号

            Log &_log;            // 引用外部的Log类,负责根据不同的策略进行刷新
            std::string _loginfo; // 一条完整的日志记录
        };

        // 这里的返回临时对象logmessage是我们故意设置的
        logmessage operator()(LogLevel level, const std::string &filename, int line)
        {
            return logmessage(level, filename, line, *this); // 新增加入*this指针，因为该Log的*this就代表该类型
        }

    private:
        std::shared_ptr<LogStrategy> _strategy;
        Mutex _mutex;
    };
    Log log;
#define LOG(Level) log(Level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() log.EnableConsoleLog()
#define ENABLE_FILE_LOG() log.EnableFileLog()
}